import SocketServer
import binascii
import sys
import time

def bytes_from_file(filename, chunksize=8192):
    with open(filename, "rb") as f:
        while True:
            chunk = f.read(chunksize)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break
                
class MyTCPHandler(SocketServer.BaseRequestHandler):
	"""
	The RequestHandler class for our server.

	It is instantiated once per connection to the server, and must
	override the handle() method to implement communication to the
	client.
	"""
	def process_cmd(self, data):
		l = data.split('|')
		if l[0] == 'PSO':
			if l[1] == 'readfile':
				try:
					print 'Esperando ...'
					time.sleep(1)
					print 'Enviando %s' % l[2]
					
					#for b in bytes_from_file(l[2]):
					#	print binascii.hexlify(b),
					#	print
					#	self.request.send(b)
					#	time.sleep(0.01)
					
					self.request.send(open(l[2], 'rb').read())
					#for x in open(l[2], 'rb').read():
					#	print binascii.hexlify(x)
					#	self.request.send(x)
					#	time.sleep(0.01)
					
					#f = open(l[2], 'rb')
					#for x in f.read(1):
					#	print binascii.hexlify(x),
					#	print
					#	self.request.send(x)
					#	time.sleep(0.01)
					#f.close()
					
					print 'Done!!'
					return True
				except:
					print 'Error Open', sys.exc_info()
					pass
		return False
		

	def handle(self):
		self.data='d'
		self.buffer= ''
		while self.data:
			self.data = self.request.recv(1)
			self.buffer += self.data
			#print "%s wrote:" % self.client_address[0]
			print self.data
			print binascii.hexlify(self.data)
			if '\n' in self.buffer or  '\0' in self.buffer:
				print 'Procesando Comando'
				print self.buffer
				if not self.process_cmd(self.buffer.rstrip('\n')):
					# just send back the same data, but upper-cased
					self.request.send(self.buffer.upper())
				self.buffer = ''



if __name__ == "__main__":
	HOST, PORT = "localhost", 8888

	# Create the server, binding to localhost on port 9999
	server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

	# Activate the server; this will keep running until you
	# interrupt the program with Ctrl-C
	server.serve_forever()

